<template>
  <section class="main-content">
    <el-card v-if="props.NewArticle" class="post-card">
      <div class="post-header">
        <router-link :to="`/userinfo?id=${userinfo.id}`">
          <img
            :src="userinfo.avatar || '/assets/avatar/default.jpg'"
            alt="Avatar"
            class="user-avatar"
          />
        </router-link>
        <router-link :to="`/userinfo?id=${userinfo.id}`">
          <span class="username">{{ userinfo.username }}</span>
        </router-link>
        <span class="prompt">，分享你的新鲜事吧！</span>
      </div>
      <input
        type="text"
        placeholder="在这里输入内容"
        class="search-input"
        style="width: 100%"
        @click="router.push('/article')"
      />
    </el-card>
    <el-card
      v-if="paginatedArticles"
      v-for="article in paginatedArticles"
      :key="article.id"
      class="post-show-card"
      :body-style="{ padding: '20px 20px 0px' }"
    >
      <div class="post-header">
        <router-link
          :to="`/userinfo?id=${article.user_id}`"
          style="display: flex; align-items: flex-start"
        >
          <img
            :src="article.avatar != null ? article.avatar : '/assets/avatar/default.jpg'"
            class="user-avatar"
          />
          <div style="display: flex; flex-direction: column; margin-left: 15px">
            <span class="username">{{ article.username }}</span>
            <span class="time">{{ article.time }}</span>
          </div>
        </router-link>
        <el-button
          v-if="article.user_id !== user.id"
          @click.stop="handleFollow(article.user_id)"
          type="text"
          size="small"
          style="align-self: flex-start"
          :class="{ 'is-following': isFollowing(article.user_id) }"
        >
          {{ isFollowing(article.user_id) ? "已关注" : "关注" }}
        </el-button>
      </div>
      <p class="post-content">
        <span class="post-tag">{{ article.tag }}</span>
        {{ article.content }}
      </p>
      <img
        v-if="article.img"
        :src="article.img"
        alt="Post Image"
        class="post-image"
        @click="showImageDialog(article.img)"
      />
      <div class="post-stats">
        <div class="stats-left">
          <span>{{ article.likes }}人点赞</span>
        </div>
        <div class="stats-right">
          <span style="margin-right: 10px">{{ article.comments }}条评论</span>
          <span>{{ article.shares }}次分享</span>
        </div>
      </div>
      <div class="post-actions">
        <el-button text @click="handleLike(article.id)">
          <template v-if="article.like.includes(user.id)">
            <el-icon style="color: #409eff"><StarFilled /></el-icon>
            <span style="color: #409eff">已点赞</span>
          </template>
          <template v-else>
            <el-icon style="color: #65676b"><StarFilled /></el-icon>
            <span style="color: #65676b">点赞</span>
          </template>
        </el-button>
        <el-button text @click="handleComment(article.id)">
          <el-icon style="color: #65676b"><Comment /></el-icon>
          <span style="color: #65676b">评论</span>
        </el-button>
        <el-button text @click="copyArticleLink(article.id)">
          <el-icon style="color: #65676b"><Share /></el-icon>
          <span style="color: #65676b">分享</span>
        </el-button>
      </div>
    </el-card>
    <el-pagination
      style="margin: auto"
      v-if="articles.length > pageSize"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="articles.length"
      layout="prev, pager, next"
      @current-change="handlePageChange"
    />

    <el-skeleton v-if="isLoading" :count="pageSize" animated>
      <!-- 模拟文章卡片 -->
      <template #template>
        <div style="height: 200px; padding: 20px 20px 0px" class="post-show-card">
          <div class="post-header">
            <el-skeleton-item variant="image" class="user-avatar" />
            <div style="width: 20%;">
              <el-skeleton-item variant="text" class="username" />
              <el-skeleton-item variant="text" class="time" />
            </div>
          </div>
          <div class="post-stats" style="display: block">
            <div class="stats-left">
              <el-skeleton-item variant="text" />
            </div>
            <div class="stats-right">
              <el-skeleton-item variant="text" />
              <el-skeleton-item variant="text" />
            </div>
          </div>
          <div class="post-actions">
            <el-skeleton-item variant="text" />
            <el-skeleton-item variant="text" />
            <el-skeleton-item variant="text" />
          </div>
        </div>
      </template>
    </el-skeleton>
  </section>
  <el-dialog
    v-model="dialogVisible"
    width="50%"
    append-to-body
    :show-close="false"
    style="padding: 0"
    class="dialog-bar"
  >
    <img :src="dialogImageUrl" class="dialog-image" />
  </el-dialog>
  
</template>

<script setup>
import { StarFilled, Comment, Share } from "@element-plus/icons-vue";
import { ref, onMounted, watch, computed } from "vue";
import userStore from "../store/index";
import { useRoute, useRouter } from "vue-router";
import api from "../utils/index.js";
import { ElMessage } from "element-plus";
import { ElSkeleton } from "element-plus";

//获取当前用户信息，路由，文章列表
const router = useRouter();
const route = useRoute();
const userStoreInfo = userStore();
const user = userStoreInfo.getUser();
const userinfo = ref({});
const articles = ref([]);

//加载
const isLoading = ref(true);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(5); // 每页显示的文章数量

// 计算当前页的文章列表
const paginatedArticles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return articles.value.slice(start, end);
});

//接受父组件传递的文章列表
const props = defineProps({
  articles: {
    type: Array,
    default: () => [],
  },
  NewArticle: {
    type: Object,
    default: null,
  },
});

// 提取获取用户信息的逻辑
const fetchUserInfo = async () => {
  try {
    const response = await api.get(`/users?id=${user.id}`);
    userinfo.value = response.data[0];
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 提取过滤文章的逻辑，并根据路由参数进行过滤
const filterArticles = (allArticles) => {
  const { name } = router.currentRoute.value;
  const section = route.query.section;

  if (name === "userinfo" || name === "search") {
    return props.articles;
  }

  if (section === undefined) {
    return allArticles;
  }

  if (section === "contact") {
    const contactIds = userinfo.value.contact || [];
    return contactIds.length > 0
      ? allArticles.filter((article) => contactIds.includes(article.user_id))
      : [];
  }

  return allArticles.filter((article) => article.tag === section);
};

// 提取获取文章的逻辑（修改部分）
const fetchArticles = async () => {
  try {
    const { data: allArticles } = await api.get(`/articles`);
    const filteredArticles = filterArticles(allArticles);

    articles.value = await Promise.all(
      filteredArticles.map(async (article) => {
        try {
          // 获取用户数据时添加错误处理
          const { data: userData } = await api.get(`users?id=${article.user_id}`);

          // 检查用户数据是否存在
          const userInfo =
            userData?.length > 0
              ? userData[0]
              : {
                  username: "未知用户",
                  avatar: "/assets/avatar/default.jpg",
                };

          return {
            ...article,
            username: userInfo.username,
            avatar: userInfo.avatar,
          };
        } catch (userError) {
          // 用户数据获取失败时使用默认值
          console.error(`获取用户${article.user_id}信息失败:`, userError);
          return {
            ...article,
            username: "未知用户",
            avatar: "/assets/avatar/default.jpg",
          };
        }
      })
    );
    // 重置页码
    currentPage.value = 1;
  } catch (error) {
    console.error("获取文章失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 初始化数据
onMounted(async () => {
  await fetchUserInfo();
  await fetchArticles();
});

// 监听路由变化
watch(() => route.query.section, fetchArticles, { deep: true });

// 评论
const handleComment = (id) => {
  router.push({ path: "/articleinfo", query: { id } });
};

// 修改点赞方法
const handleLike = async (id) => {
  const articleIndex = articles.value.findIndex((article) => article.id === id);
  if (articleIndex === -1) return;

  const article = articles.value[articleIndex];
  const isLiked = article.like.includes(user.id);

  try {
    if (isLiked) {
      // 取消点赞
      await api.patch(`/articles/${id}`, {
        likes: article.likes - 1,
        like: article.like.filter((userId) => userId !== user.id),
      });
      // 更新本地状态
      article.likes -= 1;
      article.like = article.like.filter((userId) => userId !== user.id);
    } else {
      // 点赞
      await api.patch(`/articles/${id}`, {
        likes: article.likes + 1,
        like: [...article.like, user.id],
      });
      // 更新本地状态
      article.likes += 1;
      article.like.push(user.id);
    }
    articles.value.splice(articleIndex, 1, article);
  } catch (error) {
    console.error(isLiked ? "取消点赞失败:" : "点赞失败:", error);
  }
};

// 复制文章链接到剪贴板的方法
const copyArticleLink = (id) => {
  const baseUrl = window.location.origin;
  const articleUrl = `${baseUrl}/articleinfo?id=${id}`;
  navigator.clipboard
    .writeText(articleUrl)
    .then(() => {
      ElMessage.success("文章链接已复制到剪贴板");
    })
    .catch((err) => {
      ElMessage.error("复制链接失败: " + err);
    });
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

// 定义对话框相关的响应式数据
const dialogVisible = ref(false);
const dialogImageUrl = ref("");

// 显示图片放大对话框的方法
const showImageDialog = (imageUrl) => {
  dialogImageUrl.value = imageUrl;
  dialogVisible.value = true;
};
// 在script setup部分添加以下代码
const isFollowing = (userId) => {
  return userinfo.value.contact?.includes(userId);
};

const handleFollow = async (userId) => {
  try {
    const isFollowing = userinfo.value.contact?.includes(userId);
    let newContacts = [...(userinfo.value.contact || [])];

    if (isFollowing) {
      newContacts = newContacts.filter((id) => id !== userId);
      await api.patch(`/users/${user.id}`, { contact: newContacts });
      ElMessage.success("已取消关注");
    } else {
      newContacts.push(userId);
      await api.patch(`/users/${user.id}`, { contact: newContacts });
      ElMessage.success("关注成功");
    }

    // 更新本地状态
    userinfo.value.contact = newContacts;
    userStoreInfo.setUser({ ...userinfo.value });
  } catch (error) {
    ElMessage.error(isFollowing ? "取消关注失败" : "关注失败");
  }
};
</script>

<style scoped>
.main-content {
  background-color: transparent;
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
}

.post-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.post-card:hover {
  transform: translateY(-2px);
}

.post-show-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.post-show-card:hover {
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #1c1e21;
}

.time {
  color: #999;
  font-size: 12px;
  margin-top: 2px;
}

.post-input {
  width: 100%;
  margin-bottom: 5px;
}

.search-input:focus {
  outline: none;
  border-color: #409eff;
}

.post-content {
  text-align: left;
  margin: 0 0 10px;
  font-size: 15px;
  line-height: 1.6;
  color: #1c1e21;
}

.post-tag {
  background-color: #0055ffa6;
  color: #fff;
  padding: 4px 8px;
  border-radius: 20px;
  display: inline-block;
}

.post-image {
  width: 33%;
  height: auto;
  border-radius: 12px;
  object-fit: cover;
}

.post-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e4e6eb;
  color: #65676b;
  font-size: 14px;
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 8px 0;
}

.post-actions .el-button {
  flex: 1;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s ease;
}

.post-actions .el-button:hover {
  background-color: #f0f2f5;
}

.dialog-image {
  width: 100%;
  height: auto;
}
.is-following {
  color: #409eff;
}
.el-button.is-following:hover {
  color: #ff4d4f;
}
</style>
<style>
.dialog-bar .el-dialog__header {
  padding-bottom: 0;
}
</style>
